import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { getUserDrawings, deleteDrawing as deleteDrawingFromBackend, setDrawingPublic } from '../utils/drawingApi';
import type { DrawingType } from '../types/drawing';
import ThemeToggle from '../components/ui/ThemeToggle';
import { saveDrawing as saveDrawingToBackend } from '../utils/drawingApi';
import MagnifierTooltip from '../components/ui/MagnifierTooltip';

type SavedDrawing = {
  id: string;
  dataUrl: string;
  timestamp: string;
  type?: DrawingType;
  randomDelay?: number;
  title?: string;
  backendId?: string;
  backendSyncFailed?: boolean;
  aiPrediction?: string;
  accuracy?: number;
  isPublic?: boolean;
};

const SavedDrawingsPage: React.FC = () => {
  const { isAuthenticated, user } = useAuth();
  const [drawings, setDrawings] = useState<SavedDrawing[]>([]);
  const [selectedDrawing, setSelectedDrawing] = useState<SavedDrawing | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const loadDrawings = async () => {
      if (!isAuthenticated || !user) {
        // 如果未登录，尝试从本地存储加载
        try {
          const saved = localStorage.getItem('seaSkyDrawings');
          if (saved) {
            setDrawings(JSON.parse(saved));
          }
        } catch (error) {
          console.error('Failed to load local drawings:', error);
          setError('加载本地画作失败');
        }
        setLoading(false);
        return;
      }

      try {
        setLoading(true);
        setError(null);
        
        // 从后端获取用户画作
        const backendResponse = await getUserDrawings(user.id);
        
        // 转换后端数据格式为组件所需格式
        const convertedDrawings: SavedDrawing[] = backendResponse.data.map(drawing => ({
          id: drawing.id.toString(),
          dataUrl: drawing.imageData,
          timestamp: new Date(drawing.createdAt).toLocaleString(),
          type: drawing.drawingType,
          title: drawing.title,
          backendId: drawing.id.toString(),
          aiPrediction: drawing.aiPrediction,
          accuracy: drawing.aiAccuracy,
          isPublic: drawing.isPublic
        }));
        
        // 同时从本地存储获取可能未同步的画作
        const localDrawings: SavedDrawing[] = [];
        try {
          const saved = localStorage.getItem('seaSkyDrawings');
          if (saved) {
            const parsed = JSON.parse(saved);
            // 只保留未同步到后端的画作
            localDrawings.push(...parsed.filter((d: any) => d.backendSyncFailed || !d.backendId));
          }
        } catch (localError) {
          console.error('Failed to load local drawings:', localError);
        }
        
        // 合并后端和本地画作
        setDrawings([...convertedDrawings, ...localDrawings]);
      } catch (error) {
        console.error('Failed to load drawings from backend:', error);
        setError('加载画作失败，请重试');
        
        // 如果后端加载失败，尝试从本地存储加载
        try {
          const saved = localStorage.getItem('seaSkyDrawings');
          if (saved) {
            setDrawings(JSON.parse(saved));
          }
        } catch (localError) {
          console.error('Failed to load local drawings:', localError);
        }
      } finally {
        setLoading(false);
      }
    };

    loadDrawings();
  }, [isAuthenticated, user]);

  // 从 dataUrl 获取图片尺寸（用于在需要时重新同步到后端）
  const getImageDimensions = (dataUrl: string): Promise<{ width: number; height: number }> => {
    return new Promise((resolve, reject) => {
      const img = new Image();
      img.onload = () => resolve({ width: img.width, height: img.height });
      img.onerror = (e) => reject(e);
      img.src = dataUrl;
    });
  };

  const deleteDrawing = async (id: string) => {
    const drawing = drawings.find(d => d.id === id);
    if (!drawing) return;

    try {
      // 如果画作有后端ID且用户已登录，从后端删除
      if (drawing.backendId && isAuthenticated && user) {
        await deleteDrawingFromBackend(Number(drawing.backendId));
      }
      
      // 从本地状态和本地存储中删除
      const updated = drawings.filter((d) => d.id !== id);
      setDrawings(updated);
      
      // 更新本地存储
      try {
        const saved = localStorage.getItem('seaSkyDrawings');
        if (saved) {
          const localDrawings = JSON.parse(saved);
          const updatedLocal = localDrawings.filter((d: any) => d.id !== id && d.backendId !== drawing.backendId);
          localStorage.setItem('seaSkyDrawings', JSON.stringify(updatedLocal));
        }
      } catch (localError) {
        console.error('Failed to update local storage:', localError);
      }
    } catch (error) {
      console.error('Failed to delete drawing:', error);
      setError('删除画作失败，请重试');
      setTimeout(() => setError(null), 3000);
    }
  };

  const togglePublicStatus = async (id: string) => {
    const drawing = drawings.find(d => d.id === id);
    if (!drawing || !drawing.backendId || !isAuthenticated) return;

    try {
      // 切换公开状态
      const newPublicStatus = !drawing.isPublic;
      // 在 togglePublicStatus 内移除未使用变量，仅保留 await 调用
      await setDrawingPublic(Number(drawing.backendId), newPublicStatus);
      
      // 更新本地状态
      const updated = drawings.map(d => {
        if (d.id === id) {
          return { ...d, isPublic: newPublicStatus };
        }
        return d;
      });
      
      setDrawings(updated);
    } catch (error) {
      console.error('Failed to update drawing public status:', error);
      const msg = error instanceof Error ? error.message : String(error);
      if (msg.includes('404')) {
        // 404：云端未找到该作品，尝试自动重新同步并设置公开状态
        if (!user) {
          setError('云端未找到该作品，请登录后重试');
          setTimeout(() => setError(null), 4000);
          return;
        }
        try {
          // 组装最小可用的数据进行重新保存
          const { width, height } = await getImageDimensions(drawing.dataUrl);
          const req = {
            title: drawing.title || '未命名画作',
            imageData: drawing.dataUrl,
            drawingType: (drawing.type || 'bird') as any,
            aiPrediction: drawing.aiPrediction,
            aiAccuracy: drawing.accuracy,
            canvasWidth: width || 800,
            canvasHeight: height || 600,
            brushSettings: {
              size: 8,
              color: '#000000',
              opacity: 1,
              tool: 'brush' as const,
            },
            isPublic: !drawing.isPublic, // 目标公开状态
            tags: drawing.type,
          };
          const saved = await saveDrawingToBackend(req as any, user.id);

          // 同步本地 state 和 localStorage
          const updated = drawings.map(d => d.id === id ? { ...d, backendId: String(saved.id), backendSyncFailed: false, isPublic: req.isPublic } : d);
          setDrawings(updated);
          try {
            const savedLocalStr = localStorage.getItem('seaSkyDrawings');
            if (savedLocalStr) {
              const localDrawings = JSON.parse(savedLocalStr);
              const updatedLocal = localDrawings.map((d: any) => d.id === id ? { ...d, backendId: String(saved.id), backendSyncFailed: false, isPublic: req.isPublic } : d);
              localStorage.setItem('seaSkyDrawings', JSON.stringify(updatedLocal));
            }
          } catch (e) {
            console.error('Failed to update local storage after resync:', e);
          }
          // 提示已自动修复
          setError(null);
          return;
        } catch (resyncErr) {
          console.error('Auto resync failed:', resyncErr);
          // 重新同步失败，则标记为未同步并提示用户
          const updated = drawings.map(d => d.id === id ? { ...d, backendId: undefined, backendSyncFailed: true } : d);
          setDrawings(updated);
          try {
            const saved = localStorage.getItem('seaSkyDrawings');
            if (saved) {
              const localDrawings = JSON.parse(saved);
              const updatedLocal = localDrawings.map((d: any) => d.id === id ? { ...d, backendId: undefined, backendSyncFailed: true } : d);
              localStorage.setItem('seaSkyDrawings', JSON.stringify(updatedLocal));
            }
          } catch (localError) {
            console.error('Failed to update local storage flags:', localError);
          }
          setError('云端未找到该作品（可能已删除或同步失败）。已标记为未同步，请重新保存后再尝试设为公开。');
        }
      } else {
        setError(`${drawing.isPublic ? '取消公开' : '设为公开'}失败，请重试`);
      }
      setTimeout(() => setError(null), 4000);
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-b from-base-200 via-base-100 to-base-300 p-4">
      <div className="container mx-auto max-w-6xl">
        <div className="flex justify-between items-center mb-6">
          <h1 className="text-3xl font-bold text-base-content">我的画作</h1>
          <ThemeToggle />
        </div>

        {error && (
          <div className="alert alert-error mb-4">
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <span>{error}</span>
          </div>
        )}

        {!isAuthenticated && (
          <div className="alert alert-warning mb-4">
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <div>
              <p>您当前未登录，只能查看本地保存的画作。</p>
              <Link to="/login" className="link link-primary font-medium">点击登录</Link>
              <span>以同步云端画作。</span>
            </div>
          </div>
        )}

        {selectedDrawing && (
          <div className="modal modal-open">
            <div className="modal-box max-w-4xl">
              <button 
                className="btn btn-sm btn-circle btn-ghost absolute right-2 top-2" 
                onClick={() => setSelectedDrawing(null)}
              >
                ✕
              </button>
              
              <div className="flex flex-col lg:flex-row gap-6">
                <div className="flex-1">
                  <img 
                    src={selectedDrawing.dataUrl} 
                    alt="Selected drawing" 
                    className="w-full h-auto rounded-lg shadow-lg" 
                  />
                </div>
                
                <div className="flex-1 space-y-4">
                  {selectedDrawing.title && (
                    <h3 className="text-2xl font-bold text-base-content">{selectedDrawing.title}</h3>
                  )}
                  
                  <div className="badge badge-outline">
                    <svg className="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    {selectedDrawing.timestamp}
                  </div>
                  
                  {selectedDrawing.type && (
                    <div className="absolute top-2 left-2 badge badge-primary badge-sm">
                      <span className="text-base leading-none" role="img" aria-label={selectedDrawing.type} title={selectedDrawing.type}>
                        {TYPE_EMOJI[selectedDrawing.type]}
                      </span>
                    </div>
                  )}
                  {selectedDrawing.aiPrediction && (
                    <div className="card bg-base-200">
                      <div className="card-body p-4">
                        <h4 className="card-title text-lg">AI识别结果</h4>
                        <p><strong>识别为：</strong>{selectedDrawing.aiPrediction}</p>
                        {selectedDrawing.accuracy && (
                          <div className="flex items-center gap-2">
                            <span><strong>准确度：</strong></span>
                            <div className="radial-progress text-primary" style={{"--value": selectedDrawing.accuracy} as React.CSSProperties}>
                              {selectedDrawing.accuracy}%
                            </div>
                          </div>
                        )}
                      </div>
                    </div>
                  )}
                  
                  {selectedDrawing.backendSyncFailed && (
                    <div className="alert alert-warning">
                      <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
                      </svg>
                      <span>此画作未同步到云端</span>
                    </div>
                  )}
                </div>
              </div>
            </div>
            <div className="modal-backdrop" onClick={() => setSelectedDrawing(null)}></div>
          </div>
        )}

        {loading ? (
          <div className="flex flex-col items-center justify-center py-20">
            <span className="loading loading-spinner loading-lg text-primary"></span>
            <p className="mt-4 text-lg text-base-content">正在加载画作...</p>
          </div>
        ) : drawings.length === 0 ? (
          <div className="hero min-h-[400px]">
            <div className="hero-content text-center">
              <div className="max-w-md">
                <svg className="w-24 h-24 mx-auto mb-4 text-base-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                </svg>
                <h2 className="text-2xl font-bold mb-4">{isAuthenticated ? '你还没有保存任何画作' : '本地没有保存的画作'}</h2>
                <p className="mb-6 text-base-content/70">开始你的创作之旅吧！</p>
                <Link to="/draw" className="btn btn-primary btn-lg">
                  <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z" />
                  </svg>
                  去画画
                </Link>
              </div>
            </div>
          </div>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
            {drawings.map((drawing) => (
              <div key={drawing.id} className="card bg-base-100 shadow-xl hover:shadow-2xl transition-shadow duration-300">
                <figure className="relative cursor-pointer bg-white/90 p-2 rounded-t-2xl" onClick={() => setSelectedDrawing(drawing)}>
                  <MagnifierTooltip 
                    imageUrl={drawing.dataUrl}
                    title={drawing.title || '未命名画作'}
                  >
                    <img 
                      src={drawing.dataUrl} 
                      alt={drawing.title || `Drawing ${drawing.id}`} 
                      className="w-full h-48 object-cover hover:scale-110 transition-transform duration-300 rounded-lg"
                    />
                  </MagnifierTooltip>
                  {drawing.type && (
                    <div className="absolute top-2 left-2 badge badge-primary badge-sm">
                      <span className="text-base leading-none" role="img" aria-label={drawing.type} title={drawing.type}>
                        {TYPE_EMOJI[drawing.type]}
                      </span>
                    </div>
                  )}
                  {drawing.backendSyncFailed && (
                    <div className="absolute top-2 right-2 tooltip tooltip-left" data-tip="未同步到云端">
                      <div className="badge badge-warning badge-sm">
                        <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
                        </svg>
                      </div>
                    </div>
                  )}
                </figure>
                
                <div className="card-body p-4">
                  <h3 className="card-title text-base">{drawing.title || '未命名画作'}</h3>
                  <div className="flex items-center gap-1 text-sm text-base-content/70">
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    {drawing.timestamp}
                  </div>
                  {drawing.aiPrediction && (
                    <div className="badge badge-secondary badge-sm mt-2">
                      AI: {drawing.aiPrediction}
                    </div>
                  )}
                  
                  <div className="card-actions justify-end mt-4">
                    {isAuthenticated && drawing.backendId && (
                      <button 
                        className={`btn ${drawing.isPublic ? 'btn-warning' : 'btn-success'} btn-sm`}
                        onClick={() => togglePublicStatus(drawing.id)}
                        disabled={!isAuthenticated || !drawing.backendId || drawing.backendSyncFailed}
                      >
                        <svg className="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          {drawing.isPublic ? (
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
                          ) : (
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                          )}
                        </svg>
                        {drawing.isPublic ? '取消公开' : '公开作品'}
                      </button>
                    )}
                    <button 
                      className="btn btn-error btn-sm" 
                      onClick={() => {
                        if (window.confirm('确定要删除这幅画作吗？')) {
                          deleteDrawing(drawing.id);
                        }
                      }}
                    >
                      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                      </svg>
                      删除
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}

        <div className="flex justify-center gap-4 mt-8">
          <Link to="/" className="btn btn-outline btn-lg">
            <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" />
            </svg>
            返回首页
          </Link>
          <Link to="/draw" className="btn btn-primary btn-lg">
            <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z" />
            </svg>
            继续画画
          </Link>
        </div>
      </div>
    </div>
  );
};

export default SavedDrawingsPage;


// 新增：类型到 emoji 的映射
const TYPE_EMOJI: Record<DrawingType, string> = {
  bird: '🐦',
  fish: '🐟',
  boat: '⛵️',
};

